<!--电子书管理页-->
<template>
  <a-layout>
    <a-layout-content :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }">
      <a-form layout="inline" :model="param">
        <a-form-item>
          <a-input v-model:value="param.name" placeholder="请输入名称"/>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleQuery({pageNum: 1, pageSize: pagination.pageSize})">
            查询
          </a-button>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="add()">
            新增
          </a-button>
        </a-form-item>
      </a-form>
      <a-table
          :columns="columns"
          :row-key="record => record.id"
          :data-source="ebooks"
          :pagination="pagination"
          :loading="loading"
          @change="handleTableChange"
      >
        <template #cover="{ text: cover }">
          <img v-if="cover" :src="cover" alt="avatar" />
        </template>
        <template v-slot:category="{text, record}">
          {{ getCategoryName(text.category1Id) }} / {{ getCategoryName(text.category2Id) }}
        </template>
        <template v-slot:action="{ text, record }">
          <a-space size="small">
            <router-link :to="'/admin/doc/?ebookId=' + record.id ">
              <a-button type="primary">
                文档管理
              </a-button>
            </router-link>
              <a-button type="primary" @click="edit(record)">
                编辑
              </a-button>
              <a-popconfirm
                title="删除后不可恢复，确认删除？"
                ok-text="是"
                cancel-text="否"
                @confirm="handleDelete(record.id)"
              >
                <a-button danger>
                  删除
                </a-button>
             </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </a-layout-content>
  </a-layout>
  <!-- 编辑 -->
  <a-modal v-model:visible="modalVisible" title="电子书表单" :confirm-loading="confirmLoading" @ok="handleOk">
    <a-form
        :model="ebook"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
    >
      <a-form-item label="封面">
        <a-input v-model:value="ebook.cover" />
      </a-form-item>
      <a-form-item label="名称">
        <a-input v-model:value="ebook.name" />
      </a-form-item>
      <a-form-item label="分类">
          <a-cascader
              v-model:value="categoryIds"
              :fieldNames="{ label: 'name', value: 'id', children: 'children'}"
              :options="level1"
          />
      </a-form-item>
      <a-form-item label="描述">
        <a-input v-model:value="ebook.description" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script lang="ts">
import { SmileOutlined, DownOutlined } from '@ant-design/icons-vue';
import {defineComponent, onMounted, ref} from 'vue';
import axios from "axios";
import { message } from "ant-design-vue";
import {Tool} from "@/util/tool";

export default defineComponent({
  name: 'admin-ebook',
  components: {
    SmileOutlined,
    DownOutlined,
  },
  setup() {
    const ebooks = ref();
    // 电子书查询参数封装
    const param = ref();
    param.value ={};
    const pagination = ref({
      current: 1,
      pageSize: 3,
      total: 0
    });
    const loading = ref(false);

    const columns = [
      {
        title: '封面',
        dataIndex: 'cover',
        slots: { customRender: 'cover' }
      },
      {
        title: '名称',
        dataIndex: 'name'
      },
      {
        title: '分类',
        slots: { customRender: 'category' }
      },
      {
        title: '文档数',
        dataIndex: 'docCount'
      },
      {
        title: '阅读数',
        dataIndex: 'viewCount'
      },
      {
        title: '点赞数',
        dataIndex: 'voteCount'
      },
      {
        title: 'Action',
        key: 'action',
        slots: { customRender: 'action' }
      }
    ];

    /**
     * 数据查询
     **/
    const handleQuery = (params: any) => {
      loading.value = true;
      // 这里get传参不用拼接方法 使用params固定参数配置
      axios.get("/ebook/list", {
        params: {
          pageNum: params.pageNum,
          pageSize: params.pageSize,
          name: param.value.name
        }
      }).then((response) => {
        loading.value = false;
        const data = response.data;
        if (data.success) {
          ebooks.value = data.content.list;

          // 重置分页按钮
          pagination.value.current = params.pageNum;
          pagination.value.total = data.content.total;
        } else {
          message.error(data.message);
        }
      });
    }

    /**
     * 表格点击页码时触发
     */
    const handleTableChange = (pagination: any) => {
      console.log("看看自带的分页参数都有啥：" + JSON.stringify(pagination));
      handleQuery({
        pageNum: pagination.current,
        pageSize: pagination.pageSize
      });
    };

    // 弹出编辑框
    const modalVisible = ref(false);
    const confirmLoading = ref<boolean>(false);
    // --------表单数据-----------
    const ebook = ref();
    const edit = (record: any) => {
      modalVisible.value = true;
      // ebook.value = record; 此写法会是响应式的 编辑应该是编辑赋值的对象，通过JSON方法实现  这里封装成工具类
      // ebook.value = JSON.parse(JSON.stringify(record));
      ebook.value = Tool.copy(record);
      categoryIds.value = [ebook.value.category1Id, ebook.value.category2Id];
    };

    // 分类id数组 [100, 101] 对应：前端开发 / Vue
    const categoryIds = ref();
    // 编辑框确认
    const handleOk = () => {
      confirmLoading.value = true;
      // 保存分类id
      ebook.value.category1Id = categoryIds.value[0];
      ebook.value.category2Id = categoryIds.value[1];
      // 不像get,传params键
      axios.post("/ebook/save", ebook.value).then((resp) => {
        const data = resp.data;
        confirmLoading.value = false;
        // 成功
        if (data.success) {
          modalVisible.value = false;
          // 刷新列表
          handleQuery({
            pageNum: pagination.value.current,
            pageSize: pagination.value.pageSize
          });
        } else {
          message.error(data.message);
        }
      })
    };

    // 新增电子书
    const add = () => {
      modalVisible.value = true;
      ebook.value = {};
    };
    const handleDelete = (id:number)=> {
      axios.delete("/ebook/delete/" + id).then((resp) => {
        const data = resp.data;
        // 成功
        if (data.success) {
          // 刷新列表
          handleQuery({
            pageNum: pagination.value.current,
            pageSize: pagination.value.pageSize
          });
        }
      })
    }


    // ------ 分类表单 ------
    // 处理后的树形分类
    const level1 = ref();
    let categorys: any;

    const handleQueryCategory = () => {
      loading.value = true;
      // 这里get传参不用拼接方法 使用params固定参数配置
      axios.get("/category/all").then((response) => {
        loading.value = false;
        const data = response.data;
        if (data.success) {
          categorys = data.content;
          level1.value = [];
          level1.value = Tool.array2Tree(categorys, 0); // 自己处理成树形结构
          console.log("树形结构：", level1.value);
        } else {
          message.error(data.message);
        }
      });
    }

    // 根据id获取分类名字
    const getCategoryName = (cid: number) => {
      if (!categorys) {
        return;
      }
      let result = "";
      // 遍历所有分类
      categorys.forEach((item: any) => {
        if (item.id === cid) {
          result = item.name;
        }
      });
      return result;
    }

    onMounted(() => {
      handleQuery({
        pageNum: 1,
        pageSize: pagination.value.pageSize,
      });
      handleQueryCategory();
    });

    return {
      ebooks,
      param,
      pagination,
      loading,
      handleTableChange,
      columns,
      ebook,
      modalVisible,
      confirmLoading,
      edit,
      add,
      handleOk,
      handleDelete,
      handleQuery,
      categoryIds,
      level1,
      getCategoryName
    };
  },
});
</script>


<style scoped>
img {
  width: 50px;
  height: 50px;
}
</style>